<template>
	<view class="content">
		
		<view style="position: fixed;top: 0;left: 0; width: 500upx; height: 650upx; z-index: 999999;" v-if="imgShow">
			<image :src="poster" style="width: 100%;height: 100%;"></image>
		</view>
		
		<view style="position:fixed;top:9999rpx;z-index: -1;opacity: 0;">
			<canvas class="canvas" canvas-id="myCanvas"></canvas>
		</view>
		<button style="position: absolute;bottom: 200upx;" @click="clickImg">点击分享二维码</button>
	</view>
</template>

<script>
	var _this
	export default {
		data() {
			return {
				poster: '',
				imgURL1: '/static/miao.jpg', // 背景图
				imgURL2: '/static/love.png', // 二维码
				CanvasID: 'myCanvas',
				imgShow: false
			}
		},
		onLoad() {
			_this = this
		},
		methods: {
			async clickImg() {
				uni.showLoading({
					title: '生成中'
				});
				//canvas绘画海报
				let myctx = uni.createCanvasContext(_this.CanvasID, this);
				let _poster1 = await _this.getImageInfo(_this.imgURL1); //背景图1
				let _poster2 = await _this.getImageInfo(_this.imgURL2);
				myctx.fillRect(0, 0, uni.upx2px(550), uni.upx2px(650)); //canvas画布大小
				
				myctx.drawImage('/' + _poster1.path, 0, 0, uni.upx2px(750), uni.upx2px(1500)); //背景
				myctx.drawImage('/' + _poster2.path, uni.upx2px(180), uni.upx2px(315), uni.upx2px(400), uni.upx2px(400));
				//延迟后渲染至canvas上
				setTimeout(function() {
					myctx.draw(true, ret => {
						_this.getNewImage();
					});
				}, 600);
			},
			async getImageInfo(imgSrc) {
				//获取图片信息
				return new Promise((resolve, errs) => {
					uni.getImageInfo({
						src: imgSrc,
						success: function(image) {
							console.log('图片信息：', image.path);
							resolve(image);
						},
						fail: function(err) {
							console.log(err);
						}
					});
				});
			},
			getNewImage() {
				uni.canvasToTempFilePath({ //把当前画布指定区域的内容导出生成指定大小的图片，并返回文件路径
					canvasId: _this.CanvasID,
					quality: 1,
					complete: res => {
						_this.poster = res.tempFilePath;
						if (_this.poster) {
							_this.imgShow = true;
						}
						uni.hideLoading();
					}
				});
			},
		}
	}
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}
	
	
	.canvas {
		width: 750rpx;
		height: 1500rpx;
		opacity: 0;
	}
</style>
